import math

import numpy as np
import smbus
from adxl345 import ADXL345
import socket
from threading import Timer
import time
import urllib.request as ur
import urllib.parse

adxl345 = ADXL345()
tcp_client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 服务器内网穿透
tcp_client_socket.connect(("434b2006a8.qicp.vip", 49916))
# axes={'x':'123','y':'15615','z':'4562'}
pitch_low = 0
pitch_high = 0



def get_prp():
    axes = adxl345.get_axes(True)
    x = axes['x']
    y = axes['y']
    z = axes['z']
    # 数据处理转换
    pitch = math.degrees(np.arctan(x / np.sqrt(y * y + z * z)))
    roll = math.degrees(np.arctan(y / np.sqrt(x * x + z * z)))
    paw = math.degrees(np.arctan(np.sqrt(x * x + z * z) / x))
    return float(pitch), float(roll), float(paw)

def func():
    pitch, roll, paw=get_prp()
    print("ADXL345 on address 0x%x:" % (adxl345.address))
    print("俯视角：", pitch)
    print("左右偏侧角：", roll)
    print("竖直方向转角：", paw)

    # 判断跌倒（x轴）
    if pitch < float(-70) or pitch > float(55):
        i = 0
        pitch_arr = []
        while(i<60):
            i=i+1
            pitch2, roll, paw = get_prp()
            pitch_arr.append(pitch2)
        lenth = len(pitch_arr)
        num = np.sum(i > float(-80) or i < float(60) for i in pitch_arr)
        if num > (lenth / 3 * 2):
            print("跌倒！！！")
            tcp_client_socket.send("老人跌倒!\n".encode("utf-8"))
    # 向服务器发送数据
    else:
        tcp_client_socket.send((str(pitch) + "*" + str(roll) + "*" + str(paw) + "\n").encode("utf-8"))
    # print(type(str(pitch)))
    pass


class RepeatingTimer(Timer):
    # 定时器
    def run(self):
        while not self.finished.is_set():
            self.function(*self.args, **self.kwargs)
            self.finished.wait(self.interval)

t = RepeatingTimer(2.0, func)
t.start()
